import axios from "axios"
import { onUnmounted, ref, type Ref } from "vue"

// 类型定义
interface SuggestionItem {
    id: string
    title: string
    address?: string
    location: {
      lat: number
      lng: number
    }
}
interface PlaceItem {
    title: string
    address: string
    location: {
      lat: number
      lng: number
    }
}
interface MarkerInstance {
  setMap: (map: TMap.Map | null) => void
}

// 添加回调函数类型
type OnConfirmCallback = (place: PlaceItem) => void;

export default function(tmap: any, mapRef: Ref<TMap.Map | null>, onConfirm?: OnConfirmCallback){
  // 搜索相关
  const searchKeyword = ref<string>('')
  const suggestions = ref<SuggestionItem[]>([])
  const showSuggestions = ref<boolean>(false)
  const markers: Ref<MarkerInstance[]> = ref([])
  // 防抖处理
  let debounceTimer: any = null
  let multiMarkerInstance: any = null // 保存MultiMarker实例

  const handleInput = (): void => {
    if (debounceTimer) clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      fetchSuggestions()
    }, 300)
  }
  
  // 获取搜索建议
  const fetchSuggestions = async (): Promise<void> => {
    const keyword = searchKeyword.value.trim()
    if (!keyword) {
      suggestions.value = []
      showSuggestions.value = false
      return
    }
    const resp = await axios.get('http://localhost:3000/api/place', { params: { keyWord: keyword } })
    const { status } = resp
    const data_array = resp.data
    if(status === 200){
        const { data } = data_array
        suggestions.value = data.map((item: any) => ({
            id: `${item.location?.lat}_${item.location?.lng}`,
            title: item.title,
            address: item.address,
            location: {
              lat: item.location?.lat,
              lng: item.location?.lng
            }
        }))
        showSuggestions.value = true
    }
  }
  
  // 高亮关键词
  const highlightKeyword = (text: string): string => {
    const keyword = searchKeyword.value
    if (!keyword) return text
    const reg = new RegExp(keyword, 'gi')
    return text.replace(reg, '<span class="highlight">$&</span>')
  }
  
  // 处理建议项选择
  const handleSelectSuggestion = (item: SuggestionItem): void => {
    searchKeyword.value = item.title
    showSuggestions.value = false
    searchPlaces(item.title)
    centerMap(item.location)
  }
  
  // 执行搜索
  const handleSearch = (): void => {
    showSuggestions.value = false
    searchPlaces(searchKeyword.value)
  }
  
  // 地点搜索
  const searchPlaces = async (keyword: string): Promise<void> => {
    clearMarkers()
    const resp = await axios.get('http://localhost:3000/api/search', { params: { keyword: encodeURIComponent(keyword) } })
    const { data } = resp
    if (data.status === 0) {
      addMarkers(data.data)
    }

  }
  
  // 修改后的方法示例
  const addMarkers = (places: PlaceItem[]): void => {
    if (!mapRef.value || !tmap) return

    // 先清除旧标记
    clearMarkers()

    // 构造新的几何数据
    const geometries = places.map((place, index) => ({
      id: `marker_${Date.now()}_${index}`, // 确保唯一性
      position: new tmap.LatLng(place.location.lat, place.location.lng),
      styleId: 'defaultStyle',
      properties: {
        title: place.title,
        address: place.address
      }
    }))

    // 创建新实例
    multiMarkerInstance = new tmap.MultiMarker({
      map: mapRef.value,
      enableCollision: true, // 开启碰撞检测
      styles: {
        defaultStyle: new tmap.MarkerStyle({
          width: 24,
          height: 35,
          anchor: { x: 12, y: 35 },
          src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
        })
      },
      geometries
    })

    // 使用事件委托（新版API推荐方式）
    multiMarkerInstance.on('click', (evt: any) => {
      
      // 生成唯一的ID
      const infoWindowId = `info-window-${Date.now()}`
      
      const infoWindow = new tmap.InfoWindow({
        map: mapRef.value,
        position: evt.geometry.position,
        content: `
          <div id="${infoWindowId}" class="info-window" style="padding: 10px;">
            <h3 style="margin: 0 0 10px 0;">${evt.geometry.properties.title}</h3>
            <p style="margin: 0 0 10px 0;">${evt.geometry.properties.address}</p>
            <button onclick="window._handleMapConfirm('${infoWindowId}', '${evt.geometry.properties.title}', '${evt.geometry.properties.address}', ${evt.geometry.position.lat}, ${evt.geometry.position.lng})" 
                    style="padding: 5px 15px; background: #409EFF; color: white; border: none; border-radius: 4px; cursor: pointer;">
              确认
            </button>
          </div>
        `
      })

      // 添加全局处理函数
      ;(window as any)._handleMapConfirm = (id: string, title: string, address: string, lat: number, lng: number) => {
        if (onConfirm) {
          onConfirm({
            title,
            address,
            location: { lat, lng }
          })
        }
        infoWindow.close()
      }

      // 5秒后自动关闭并清理
      setTimeout(() => {
        infoWindow.close()
        delete (window as any)._handleMapConfirm
      }, 5000)
    })
  }

  
  // 清除标记
  const clearMarkers = (): void => {
    if (multiMarkerInstance) {
      multiMarkerInstance.setMap(null) // 关键步骤：从地图移除
      multiMarkerInstance.destroy()    // 调用官方销毁方法
      multiMarkerInstance = null
    }
  }
  
  const centerMap = (location: { lat: number; lng: number }): void => {
    if (!mapRef.value) return
    mapRef.value.setCenter(new TMap.LatLng(location.lat, location.lng))
    mapRef.value.setZoom(15)
  }
  return { searchKeyword, suggestions, showSuggestions, handleInput, highlightKeyword, handleSelectSuggestion, handleSearch  }
}